#include <stdlib.h>
#include <string.h>
#include "typedef.h"
#include "common.h"
#include "package.h"
#include "task.h"

static PTASKINFO header = NULL;
static PTASKINFO tail   = NULL;

void tsk_init()
{
	 header = NULL;
	 tail   = NULL;
}

PTASKINFO tsk_getlist()
{
	return header;
}

void tsk_add(int id, int pid, char* command)
{
	PTASKINFO temp = (PTASKINFO)malloc(sizeof(TASKINFO));

	temp->taskId = id;
	temp->pid    = pid;
	arraycopy(temp->cmd, 0, command, 0, strlen(command));
	temp->status = TASK_STAT_RUNNING;

	temp->before = NULL;
	temp->next   = NULL;

	if (header == NULL)
		header = temp;
	else
	{
		tail->next = temp;
		temp->before = tail;
	}

	tail = temp;
}

void tsk_remove(int id)
{
	PTASKINFO temp = tsk_findbyid(id);
	if (temp == NULL)
		return;

	PTASKINFO before = temp->before;
	PTASKINFO next = temp->next;

	if (before != NULL && next != NULL)
	{
		before->next = next;
		next->before = before;
	}
	else
	{
		if (before == NULL && next != NULL)
		{
			header = next;
			next->before = NULL;
		}
		else if (before != NULL && next == NULL)
		{
			tail = before;
			before->next = NULL;
		}
		else
		{
			header = NULL;
			tail = NULL;
		}
	}

	free(temp);
}

PTASKINFO tsk_findbyid(int id)
{
	PTASKINFO temp = header;
	while(temp)
	{
		if ( temp->taskId == id )
			return temp;
		temp = temp->next;
	}

	return NULL;
}

PTASKINFO tsk_findbypid(int pid)
{
	PTASKINFO temp = header;
	while(temp)
	{
		if (temp->pid == pid)
			return temp;
		temp = temp->next;
	}

	return NULL;
}

void tsk_release()
{
	PTASKINFO temp = header;
	while(temp)
	{
		header = temp->next;
		free(temp);
		temp = header;
	}

	header = tail = NULL;
}
